package com.cjy.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.cjy.dao.BlogRepository;
import com.cjy.pojo.*;
import com.cjy.pojo.vo.BlogQuery;
import com.cjy.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.*;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/admin")
public class BlogManagerController {

    @Autowired
    private BlogService blogService;

    @Autowired
    private TypeService typeService;

    @Autowired
    private TagService tagService;

    @Autowired
    private HttpSession session;

    @Autowired
    private BlogRepository blogRepository;

    @Autowired
    private ImageTypeService imageTypeService;

    @Autowired
    private FastdfsService fastdfsService;

    @Value("${fastdfs_domaint}")
    private String fastdfsDomaint;

    @RequestMapping("/blogs")
    public String blogs(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
            Pageable pageable, BlogQuery blog, Model model){
        model.addAttribute("types",typeService.listType());
        ArrayList<CheckStatus> checkStatuses = new ArrayList<>();
        checkStatuses.add(new CheckStatus(-1,"未通过"));
        checkStatuses.add(new CheckStatus(0,"审核中"));
        checkStatuses.add(new CheckStatus(1,"已通过"));
        model.addAttribute("checkStatus",checkStatuses);
        model.addAttribute("page",blogService.listBlog(pageable,blog));
        return "admin/blogManager";
    }

    @PostMapping("/search")
    public String search(@PageableDefault(size = 8,sort = {"updateTime"},direction = Sort.Direction.DESC)
                                Pageable pageable, BlogQuery blog, Model model){
        model.addAttribute("page",blogService.listBlog(pageable,blog));
        return "admin/blogManager :: blogList";
    }

    @GetMapping("/blogInput")
    public String blogInputHref(Model model){
        setTypeAndTag(model);
        Blog blog = new Blog();
        blog.setType(new Type());
        model.addAttribute("blog",blog);
        model.addAttribute("isMe",true);
        return "admin/blogInput";
    }

    public void setTypeAndTag(Model model){
        model.addAttribute("types",typeService.listType());
        model.addAttribute("tags",tagService.listTag());
    }

    @GetMapping("/blogs/{id}/input")
    public String eidtBlog(@PathVariable Long id, Model model){
        setTypeAndTag(model);
        Blog blog = blogService.getBlog(id);
        blog.init();
        model.addAttribute("blog",blog);
        User user = (User) session.getAttribute("user");
        Long userId = blogRepository.findUserId(id);
        boolean equals = userId.equals(user.getId());
        model.addAttribute("isMe", equals);

        return "admin/blogInput";
    }

    @GetMapping("/toPictureRepository")
    @ResponseBody
    public SystemResult toPictureRepository(@PageableDefault(size = 12,sort = {"createTime"},direction = Sort.Direction.DESC)
                                                Pageable pageable) {
        try {
            HashMap<String, Object> map = new HashMap<>();
            // 查询图像和图像分类
            List<ImageType> imageTypes = imageTypeService.listImageType();
            map.put("imageTypes", imageTypes);
            ImageType imageType = imageTypes.get(0);
            Map<String, Object> fasdfsFile = getFasdfsFile(imageType.getId(), pageable);
            map.put("images",fasdfsFile.get("images"));
            map.put("page",fasdfsFile.get("page"));
            map.put("total",fasdfsFile.get("total"));
            User user = (User) session.getAttribute("user");
            map.put("isRoot", user == null ? false : user.getRoleId() == 1);
            return SystemResult.ok(map);
        }catch (Exception e) {
            e.printStackTrace();
            return SystemResult.err();
        }
    }

    @GetMapping("/getPictureByType")
    @ResponseBody
    public SystemResult getPictureByType(
            @PageableDefault(size = 12,sort = {"createTime"},direction = Sort.Direction.DESC) Pageable pageable,
            @RequestParam("imageTypeId") Long imageTypeId) {
        try {
            HashMap<String, Object> map = new HashMap<>();
            Map<String, Object> fasdfsFile = getFasdfsFile(imageTypeId, pageable);
            map.put("images",fasdfsFile.get("images"));
            map.put("page",fasdfsFile.get("page"));
            map.put("total",fasdfsFile.get("total"));
            User user = (User) session.getAttribute("user");
            map.put("isRoot", user == null ? false : user.getRoleId() == 1);
            return SystemResult.ok(map);
        }catch (Exception e) {
            e.printStackTrace();
            return SystemResult.err();
        }
    }

    public Map<String,Object> getFasdfsFile(Long imageTypeId, Pageable pageable) {
        User user = (User) session.getAttribute("user");
        Page<FasdfsFile> fastDFSByImageType = fastdfsService.getFastDFSByImageType(imageTypeId, pageable);
        HashMap<String, Object> map = new HashMap<>();
        map.put("images",fastDFSByImageType.getContent().stream().map(e -> {
            e.setFileNameDfs(fastdfsDomaint + e.getFileNameDfs());
            return e;
        }).collect(Collectors.toList()).stream().filter(e -> {
            if (e.getUserId() == user.getId()) {
                return true;
            }
            return !e.getPrivate();
        }).collect(Collectors.toList()));
        map.put("total",fastDFSByImageType.getTotalPages());
        map.put("page",fastDFSByImageType.getPageable().getPageNumber());
        return map;
    }

    @PostMapping("/addBlogs")
    public String addBlogs(Blog blog, HttpSession session, RedirectAttributes attributes){

        blog.setUser((User) session.getAttribute("user"));
        blog.setType(typeService.getType(blog.getType().getId()));
        blog.setTags(tagService.listTag(blog.getTagIds()));
        blog.setThumbUpNumber(0L);
        Blog b = blogService.saveBlog(blog);
        if (b==null){
            // 保存失败
            attributes.addFlashAttribute("message","添加失败");
        }else {
            attributes.addFlashAttribute("message","添加成功");
        }
        return "redirect:/admin/blogs";
    }

    @PostMapping("/logInput/{id}")
    public String updateBlogs(@PathVariable Long id,Blog blog, HttpSession session, RedirectAttributes attributes){

        blog.setUser((User) session.getAttribute("user"));
        blog.setType(typeService.getType(blog.getType().getId()));
        blog.setTags(tagService.listTag(blog.getTagIds()));
        blog.setUpdateTime(new Date());
        blog.setThumbUpNumber(blogService.getBlog(blog.getId()).getThumbUpNumber());
        Blog b = blogService.updateBlog(id,blog);
        if (b==null){
            // 保存失败
            attributes.addFlashAttribute("message","更新失败");
        }else {
            attributes.addFlashAttribute("message","更新成功");
        }
        return "redirect:/admin/blogs";
    }

    @GetMapping("/blogs/{id}/delete")
    public String delete(@PathVariable Long id,RedirectAttributes attributes){
        blogService.deleteBlog(id);
        attributes.addFlashAttribute("message","删除成功");
        return "redirect:/admin/blogs";
    }


    // 通过审核
    @GetMapping("/passBlog")
    @ResponseBody
    public String passBlog(@RequestParam("blogId") Long blogId) {
        return blogService.passBlog(blogId);
    }

    // 打回
    @GetMapping("/rejectBlog")
    @ResponseBody
    public String rejectBlog(@RequestParam("blogId") Long blogId, @RequestParam("rejectDes") String rejectDes) {
        return blogService.rejectBlog(blogId,rejectDes);
    }
}
